package com.zxlspace.weixinseller.service.impl;

import com.zxlspace.weixinseller.DTO.CartDTO;
import com.zxlspace.weixinseller.dataobject.ProductInfo;
import com.zxlspace.weixinseller.enums.ProductStatusEnum;
import com.zxlspace.weixinseller.enums.ResultEnum;
import com.zxlspace.weixinseller.exception.SellException;
import com.zxlspace.weixinseller.repository.ProductInfoRepository;
import com.zxlspace.weixinseller.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhangxiaolin@zhonhajt.com
 * @Title: 商品业务实现类
 * @Package com.zxlspace.weixinseller.service.impl
 * @Description:
 * @date 2018/6/14 16:16
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public ProductInfo findOne(String productId) {
        return productInfoRepository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        //查询上架商品
        return productInfoRepository.findByProductStatus(ProductStatusEnum.PRODUCT_UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return  productInfoRepository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //商品加上购物车数量
            int result = productInfo.getProductStock() + cartDTO.getProductQuantity();
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            int result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            //库存不足
            if (result < 0) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //TODO 库存超卖需要控制，redis锁机制

            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }
}
